package com.hm.manage.autoInspection;

import com.hm.common.core.domain.entity.SysDept;
import com.hm.common.core.domain.entity.SysUser;
import com.hm.manage.domain.Xtxj;
import com.hm.manage.domain.Xtxjsub;
import com.hm.manage.service.IXtxjService;
import com.hm.manage.utils.*;
import com.hm.system.mapper.SysDeptMapper;
import com.hm.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 车辆相关的自动巡检
 */
@Slf4j
@Component
public class VehicleInspection {

    @Autowired
    private HikArtemisUtiles hikArtemisUtiles;

    @Autowired
    private SmsService smsService;

    @Autowired
    private FTPFileService ftpFileService;

    @Autowired
    private IXtxjService xtxjService;

    @Autowired
    private SFTPFileService sftpFileService;

    @Autowired
    private KafkaOffsetLagFetcher kafkaOffsetLagFetcher;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private DiskSpaceChecker diskSpaceChecker;

    // 逻辑是依次巡检，从下到上
    // 先判断过车是否正常，然后再去依次巡检1、ftp里的文件。2、datai服务器里面的文件.3、kafka的消费情况
    // 实现方法是分别检查各个步骤。
    // 子表的巡检序号：1、过车数量；2、ftp文件数量；3、datai服务器里面的文件 4、原始kafka消费情况；5、二次分析kafka消费情况 ;6、大数据磁盘占用情况

    public void vehicleInspection(String deptName){
        // 首先先去构造系统巡检的记录
        Xtxj xtxj = new Xtxj();
        xtxj.setXjlx("1"); //TIM公安网过车
        xtxj.setXjsj(new Date());
        xtxj.setXjly("1"); //自动
        xtxj.setXjnr("1、过车数量；2、ftp文件数量；3、datai服务器里面的文件 4、原始kafka消费情况；5、二次分析kafka消费情况；6、大数据磁盘占用情况");
        xtxj.setCreateTime(new Date());
        // 构造子表
        List<Xtxjsub> xtxjsubList = new ArrayList<>();

        // 1、过车数量
        Xtxjsub xtxjsub_gcsl = insPassCount(deptName);
        xtxjsubList.add(xtxjsub_gcsl);

        // 2、ftp文件数量
        Xtxjsub xtxjsub_ftp = insftp();
        xtxjsubList.add(xtxjsub_ftp);

        // 3、datai服务器里面的文件
        Xtxjsub xtxjsub_datai = insdataifiles();
        xtxjsubList.add(xtxjsub_datai);

        // 4、原始kafka消费情况
        Xtxjsub xtxjsub_kafka = inskafkaOragin();
        xtxjsubList.add(xtxjsub_kafka);

        // 5、二次分析kafka消费情况
        Xtxjsub xtxjsub_kafka2 = inskafkaSecond();
        xtxjsubList.add(xtxjsub_kafka2);

        // 6、大数据磁盘占用情况
        Xtxjsub xtxjsub_hbpdisk = insHbpDisk();
        xtxjsubList.add(xtxjsub_hbpdisk);

        // 综合一下巡检的结果
        StringBuilder allcon = new StringBuilder();
        StringBuilder allconcon = new StringBuilder();
        for (Xtxjsub xtxjsub : xtxjsubList) {
            allcon.append(xtxjsub.getXjjl());
            if (xtxjsub.getXjjl().equals("2")) {
                allconcon.append(xtxjsub.getXjnr()+"，实时数据量："+xtxjsub.getYl2());
            }
        }
        if (allcon.toString().contains("2")) {
            xtxj.setXjjg("2");
        } else {
            xtxj.setXjjg("1");
        }

        // 获取干系人信息
        xtxj.setXjgxr(getUsersByDeptName(deptName));

        // 保存到数据库中
        xtxj.setXtxjsubList(xtxjsubList);
        xtxjService.insertXtxj(xtxj);

        // 发送短信
        String xjjg = xtxj.getXjjg().equals("2")?"异常":"正常";
        sendSms(deptName, xjjg,allconcon.toString());
    }

    private Xtxjsub insHbpDisk() {
        Xtxjsub xtxjsub = new Xtxjsub();
        xtxjsub.setXjjl("1"); //未检测
        xtxjsub.setXh(6L);
        xtxjsub.setXjsj(new Date());
        xtxjsub.setXjnr("大数据服务器磁盘用量监测");
        xtxjsub.setCreateTime(new Date());
        xtxjsub.setXjbz("大数据服务器磁盘占用不超过80%");
        String s = diskSpaceChecker.checkGAHbpDisk();
        if (s.contains("异常")) {
            xtxjsub.setXjjl("2");
        } else {
            xtxjsub.setXjjl("1");
        }
        xtxjsub.setXjjg(s);
        xtxjsub.setYl1("大数据报盘，请参考大数据处理手册处理。");
        return xtxjsub;
    }

    /***
     *
     * @param deptName
     * @return
     */
    private String getUsersByDeptName(String deptName) {
        String xjgxr =  "";
        SysDept sysDept = new SysDept();
        sysDept.setDeptName(deptName);
        List<SysDept> sysDepts = sysDeptMapper.selectDeptList(sysDept);
        List<SysUser> sysUsers = new ArrayList<>();
        // 非空判断
        if (!sysDepts.isEmpty()) {
            for (SysDept sysDept1 : sysDepts) {
                // 获取部门下的所有人员的手机号码
                SysUser sysUser = new SysUser();
                sysUser.setDeptId(sysDept1.getDeptId());
                sysUsers = sysUserMapper.selectUserList(sysUser);
            }
        }
        for (SysUser sysUser : sysUsers) {
            if (sysUser.getUserId() == 1 || sysUser.getPhonenumber().isEmpty() || Objects.equals(sysUser.getDelFlag(), "2") || sysUser.getStatus().equals("1")) {
                log.info("----------------{}---{}",sysUser.getUserName(),"不需要发短信：为管理员或手机号为空");
                continue;
            }
            xjgxr =xjgxr+sysUser.getNickName()+"["+sysUser.getPhonenumber()+"];";
        }
        return xjgxr;
    }

    private void sendSms(String deptName, String xjjg ,String allconcon) {
        String content = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "TIM公安网过车巡检已完成，巡检结果为："+ xjjg +";详情登录不点睛平台查看具体巡检内容";
        smsService.sendtoUserByDeptName(deptName,content);
        if (!allconcon.isEmpty()) {
            smsService.sendtoUserByDeptName(deptName,"TIM公安网过车巡检异常项为"+allconcon);
        }

    }

    /***
     * 二次分析kafka消费情况
     * connector-chain-bayonet_vehiclepass
     * BAYONET_VEHICLEPASS
     * @return
     */
    private Xtxjsub inskafkaSecond() {
        Xtxjsub xtxjsub_kafka2 = new Xtxjsub();
        xtxjsub_kafka2.setXh(5L);
        xtxjsub_kafka2.setXjnr("大数据二次分析kafka消费情况");
        xtxjsub_kafka2.setXjsj(new Date());
        xtxjsub_kafka2.setXjjl("3"); //未检测
        xtxjsub_kafka2.setXjbz("kafka单片堆积数量大于2000");
        String kaficon = "正常";
        Map<Integer, Long> bayonetVehiclepassJsonTopic = kafkaOffsetLagFetcher.getLagMap("50.58.191.82:9092", "connector-chain-bayonet_vehiclepass", "BAYONET_VEHICLEPASS");
        Long maxLag = kafkaOffsetLagFetcher.getMaxLag(bayonetVehiclepassJsonTopic);
        Double averageLag = kafkaOffsetLagFetcher.getAverageLag(bayonetVehiclepassJsonTopic);
        String checkLagMap = kafkaOffsetLagFetcher.checkLagMap(bayonetVehiclepassJsonTopic);
        if (maxLag > 2000) {
            kaficon = "异常，最大分片堆积数量为"+maxLag+"，大于2000,平均为"+averageLag+";所有分片堆积数量为:"+bayonetVehiclepassJsonTopic.toString();
            xtxjsub_kafka2.setXjjl("2");
        } else {
            kaficon = "正常,"+checkLagMap+";所有分片堆积数量为:"+bayonetVehiclepassJsonTopic.toString();
            xtxjsub_kafka2.setXjjl("1");
        }
        xtxjsub_kafka2.setXjjg(kaficon);
        xtxjsub_kafka2.setYl1("请检查kafka消费组connector-chain-bayonet_vehiclepass堆积情况,建议重启流水，或增加消费线程");

        return xtxjsub_kafka2;
    }

    /***
     * kafka原始消费情况
     * connector-chain-bayonet_vehiclepass_convert
     * BAYONET_VEHICLEPASS_JSON_TOPIC
     * @return
     */
    private Xtxjsub inskafkaOragin() {
        Xtxjsub xtxjsub_kafka = new Xtxjsub();
        xtxjsub_kafka.setXh(4L);
        xtxjsub_kafka.setXjnr("大数据原始kafka消费情况");
        xtxjsub_kafka.setXjsj(new Date());
        xtxjsub_kafka.setXjjl("3"); //未检测
        xtxjsub_kafka.setXjbz("kafka堆积数量大于2000");
        String kaficon = "正常";
        Map<Integer, Long> bayonetVehiclepass = kafkaOffsetLagFetcher.getLagMap("50.58.191.82:9092", "connector-chain-bayonet_vehiclepass_convert", "BAYONET_VEHICLEPASS_JSON_TOPIC");
        Long maxLag = kafkaOffsetLagFetcher.getMaxLag(bayonetVehiclepass);
        Double averageLag = kafkaOffsetLagFetcher.getAverageLag(bayonetVehiclepass);
        String checkLagMap = kafkaOffsetLagFetcher.checkLagMap(bayonetVehiclepass);
        if (maxLag > 2000) {
            kaficon = "异常，最大分片堆积数量为"+maxLag+"，大于2000,平均为"+averageLag+";所有分片堆积数量为:"+bayonetVehiclepass.toString();
            xtxjsub_kafka.setXjjl("2");
        } else {
            kaficon = "正常,"+checkLagMap+";所有分片堆积数量为:"+bayonetVehiclepass.toString();
            xtxjsub_kafka.setXjjl("1");
        }
        xtxjsub_kafka.setXjjg(kaficon);
        xtxjsub_kafka.setYl1("请检查kafka消费组connector-chain-bayonet_vehiclepass_convert堆积情况,建议重启流水，或增加消费线程");

        return xtxjsub_kafka;
    }

    private Xtxjsub insdataifiles() {
        // 3、datai服务器里面的文件
        Xtxjsub xtxjsub_datai = new Xtxjsub();
        xtxjsub_datai.setXh(3L);
        xtxjsub_datai.setXjnr("datai服务器里面的文件");
        xtxjsub_datai.setXjsj(new Date());
        xtxjsub_datai.setXjjl("3"); //未检测
        xtxjsub_datai.setXjbz("datai文件数量大于20");
        String dataicon = "正常";
        // 直接用SFTP协议获取文件数量
        String pwd = "/opt/opsmgr/web/components/datai.1/bin/datai-engine/config/vehicle_pass_inter_data_cascade_from_3204123200001";
        Integer fileCount = sftpFileService.getFileCount("50.58.185.210", 55555, "hik", "wujin320@2019", pwd);
        Integer fileCount1 = sftpFileService.getFileCount("50.58.191.99", 55555, "hik", "GA_xfhkfwq1801", pwd);
        Integer fileCount2 = sftpFileService.getFileCount("50.58.185.235", 55555, "hik", "wujin320@2019", pwd);
        Integer fileCount9 = sftpFileService.getFileCount("50.58.185.206", 55555, "hik", "wujin320@2019", pwd);
        if (fileCount > 20) {
            dataicon = "50.58.185.210FTP1异常，文件数量为"+fileCount+"，大于20;<br>";
        } else if (fileCount1 > 20) {
            dataicon = dataicon+"50.58.191.99FTP2异常，文件数量为"+fileCount1+"，大于20;<br>";
        } else if (fileCount2 > 20) {
            dataicon = dataicon+"50.58.185.235FTP3异常，文件数量为"+fileCount2+"，大于20;<br>";
        } else if (fileCount9 > 20) {
            dataicon = dataicon+"50.58.185.206FTP9异常，文件数量为"+fileCount9+"，大于20;<br>";
        } else {
            dataicon = "正常,50.58.185.210FTP1文件数量为"+fileCount+";<br>50.58.191.99FTP2文件数量为"+fileCount1+";<br>50.58.185.235FTP3文件数量为"+fileCount2+";<br>50.58.185.206FTP9文件数量为"+fileCount9;
        }
        xtxjsub_datai.setXjjg(dataicon);
        if (dataicon.contains("异常")) {
            xtxjsub_datai.setXjjl("2");
        } else {
            xtxjsub_datai.setXjjl("1");
        }
        xtxjsub_datai.setYl1("请检查有堆积的服务器的消费服务");

        return xtxjsub_datai;
    }

    /***
     * 处理过车巡检
     * @param deptName
     * @return
     */
    private Xtxjsub insPassCount(String deptName) {
        // 先调用接口获取过车数量
        Xtxjsub xtxjsub_gcsl = new Xtxjsub();
        xtxjsub_gcsl.setXh(1L);
        xtxjsub_gcsl.setXjnr("过车数量");
        xtxjsub_gcsl.setXjsj(new Date());
        xtxjsub_gcsl.setXjjl("3");
        xtxjsub_gcsl.setXjbz("400万过车");
        String con = "正常";
        // 按照2025-04-16T00:00:00.000+08:00的格式来创建时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String endTime = sdf.format(new Date()); // 如需指定具体时间可 new Date(特定时间戳)
        String beginTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +"T00:00:00.000+08:00";
        Integer passCount = hikArtemisUtiles.getCurrentVehiclePassCountByTime(beginTime, endTime);
        if (passCount < 4000000) {
            con = "异常，少于均值400万";
            log.info("公安网过车截止8:30分数量为：{}",passCount);
            if (passCount.equals(0)) {
                con = "异常，接口调用失败";
            }
        }
        xtxjsub_gcsl.setYl2(passCount+"");
        // 发送短信
        String content = "公安网过车截止"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"数量为："+passCount+"过车状态："+con;
        log.info("---------------content:{}",content);
        //smsService.sendtoUserByDeptName(deptName,content);
        xtxjsub_gcsl.setXjjg(content);
        // 如果过车正常，则直接返回
        if (con.equals("正常")){
            xtxjsub_gcsl.setXjjl("1");
        } else {
            xtxjsub_gcsl.setXjjl("2");
        }
        // 推荐措施
        xtxjsub_gcsl.setYl1("过车数量异常，请按照下面的流程依次排查。");
        return xtxjsub_gcsl;
    }

    /***
     * ftp巡检
     * @return
     */
    private Xtxjsub insftp() {
        // 如果过车异常，则继续判断ftp文件数量，如果ftp文件数量正常，则直接返回
        Xtxjsub xtxjsub_ftp = new Xtxjsub();
        xtxjsub_ftp.setXh(2L);
        xtxjsub_ftp.setXjnr("ftp文件数量");
        xtxjsub_ftp.setXjsj(new Date());
        xtxjsub_ftp.setXjjl("3");
        xtxjsub_ftp.setXjbz("ftp堆积数量大于50");
        String ftpcon = "正常";
        Integer fileCount1 = ftpFileService.getFileCount("50.58.191.199", 21, "hzjftp", "hzjftp123!", "/FTP1");
        Integer fileCount2 = ftpFileService.getFileCount("50.58.191.199", 21, "hzjftp", "hzjftp123!", "/FTP2");
        Integer fileCount3 = ftpFileService.getFileCount("50.58.191.199", 21, "hzjftp", "hzjftp123!", "/FTP3");
        Integer fileCount9 = ftpFileService.getFileCount("50.58.191.199", 21, "hzjftp", "hzjftp123!", "/FTP9");

        if (fileCount1 > 50) {
            ftpcon = "ftp1异常，文件数量为"+fileCount1+"，大于50;<br>";
        } else if (fileCount1 < 50){
            ftpcon = "ftp1正常，文件数量为"+fileCount1+";<br>";
        }
        if (fileCount2 > 50) {
            ftpcon = ftpcon+"ftp2异常，文件数量为"+fileCount2+"，大于50;<br>";
        } else if (fileCount2 < 50) {
            ftpcon = ftpcon+"ftp2正常，文件数量为"+fileCount2+";<br>";
        }
        if (fileCount3 > 50) {
            ftpcon = ftpcon+"ftp3异常，文件数量为"+fileCount3+"，大于50;<br>";
        } else if (fileCount3 < 50) {
            ftpcon = ftpcon+"ftp3正常，文件数量为"+fileCount3+";<br>";
        }
        if (fileCount9 > 50) {
            ftpcon = ftpcon+"ftp9异常，文件数量为"+fileCount3+"，大于50;<br>";
        } else if (fileCount3 < 50) {
            ftpcon = ftpcon+"ftp9正常，文件数量为"+fileCount3+";<br>";
        }
        xtxjsub_ftp.setXjjg(ftpcon);
        if (ftpcon.contains("异常")) {
            xtxjsub_ftp.setXjjl("2");
        } else {
            xtxjsub_ftp.setXjjl("1");
        }
        xtxjsub_ftp.setYl1("ftp文件堆积，去对应ftp查看。");
        log.info("----------------insftpftp巡检--------------------------");
        log.info(xtxjsub_ftp.toString());
        return xtxjsub_ftp;
    }


}
